package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @DubboReference
    private VideoApi videoApi;
    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FdfsWebServer webServer;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private MqMessageService mqMessageService;

    //上传短视频
    public void video(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
//第一步.将文件存储到服务上
        //需要四个参数：
        //1.获取文件输入流
        InputStream inputStream = videoFile.getInputStream();
        //2.获取文件大小
        long size = videoFile.getSize();
        //3.获取文件后缀名
        String name = videoFile.getOriginalFilename();
        //获取最后一个.的索引
        int index = name.lastIndexOf(".");
        name = name.substring(index + 1);
        //4.文件原始信息一般为null
        StorePath storePath = client.uploadFile(inputStream, size, name, null);
        //5.组装短视频路径
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
//第二步，将图片上传到阿里云
        //1.获取到图片的输入流
        InputStream pic = videoThumbnail.getInputStream();
        String picUrl = ossTemplate.upload(pic, videoThumbnail.getOriginalFilename());
//第三步，将地址保存到数据库中
        //1.构建对象
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setText("老八爱吃奥利给");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        videoApi.saveVideo(video);
    }

    //查找小视频列表
    public PageResult findList(Integer page, Integer pagesize) {
        //1.构建UserInfo对象，需要用户id VIDEOS_RECOMMEND_106
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        //2.获取到redis中存储的value
        String value =  redisTemplate.opsForValue().get(key);
        //3.判断一下value是不是为空
        List<Video> list = new ArrayList<>();
        if (!StringUtils.isEmpty(value)) {
            //当redis中有推荐数据的时候
            String[] ids = value.split(",");
            //查询出所有的video对象
            list = videoApi.findList(ids, page, pagesize);
        } else {
            //当redis中没有数据的时候,就查询所有的视频
            list = videoApi.findAll(page, pagesize);
        }
        //从list中获取到所有的id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> userInfos = userInfoApi.findByIds(ids);
        //循环list，构建出返回的对象
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            Long userId = video.getUserId();
            //1.取出userInfo
            UserInfo info = userInfos.get(userId);
            VideoVo vo = VideoVo.init(info, video);
            vos.add(vo);
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

    //短视频点赞操作
    public void like(String videoId) {
        // todo 以上是业务代码

        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //这里发送RabbitMq日志消息
            //需要四个参数  用户id，日志消息类型，键，视频id
        mqMessageService.sendLogMessage(userId,"0302","log.video",videoId);
    }
}
